package com.zoroki.hmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoroki.hmusic.entity.Favorite;
import com.zoroki.hmusic.entity.FavoritePlaylist;
import com.zoroki.hmusic.entity.FavoriteSong;
import com.zoroki.hmusic.entity.Playlist;
import com.zoroki.hmusic.mapper.FavoritePlaylistMapper;
import com.zoroki.hmusic.service.IFavoritePlaylistService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoroki.hmusic.service.IFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@Service
@Slf4j
public class FavoritePlaylistServiceImpl extends ServiceImpl<FavoritePlaylistMapper, FavoritePlaylist> implements IFavoritePlaylistService {

    @Autowired
    private IFavoriteService favoriteService;

    @Autowired
    private FavoritePlaylistMapper favoritePlaylistMapper;

    @Override
    public int deleteFavoritePlaylistByUserId(int userId, int playlistId) {
        //1.通过userId查询到favoriteId
        Favorite favorite = favoriteService.findFavoriteByUserId(userId);
        if (favorite == null) {
            log.error("无法找到favorite");
            return -1;
        }

        //2.通过favoriteId 和 songId 删除记录
        QueryWrapper<FavoritePlaylist> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_id", favorite.getId())
                .eq("playlist_id", playlistId);

        return favoritePlaylistMapper.delete(wrapper);
    }

    @Override
    public int deleteFavoritePlaylistByPlaylistId(int playlistId) {
        QueryWrapper<FavoritePlaylist> wrapper = new QueryWrapper<>();
        wrapper.eq("playlist_id", playlistId);
        return favoritePlaylistMapper.delete(wrapper);
    }

    @Override
    public int addPlaylistToFavorite(FavoritePlaylist favoritePlaylist) {
        QueryWrapper<FavoritePlaylist> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_id", favoritePlaylist.getFavoriteId());
        wrapper.eq("playlist_id", favoritePlaylist.getPlaylistId());
        FavoritePlaylist fp = favoritePlaylistMapper.selectOne(wrapper);
        if (fp != null) {
            return -1;
        }
        return favoritePlaylistMapper.insert(favoritePlaylist);
    }

    @Override
    public FavoritePlaylist checkPlaylistIsFavorite(int favoriteId, int playlistId) {

        QueryWrapper<FavoritePlaylist> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_id", favoriteId);
        wrapper.eq("playlist_id", playlistId);

        return favoritePlaylistMapper.selectOne(wrapper);
    }
}
